import {
	SHOP_SHOP_CAR,
	SHOP_SHOP_CAR_INFO,
	SHOP_SHOP_CAR_CLEAR,
} from '../mutation_types'

const state = {
	shop_car: [], // 购物车商品列表 购物车 
	shop_money: 0.00, //  总金额 
	shop_number: 0, // 总数量
}

const mutations = {
	// value == obj 包含 id 需要操作的对象id; type ==  ‘plus’ 加 ‘reduce’ 减  ‘delete’ 删除 ; obj 新增用到 
	[SHOP_SHOP_CAR]: (state, value) => {
		let car = state.shop_car || []

		// 进行 增删改查 操作
		switch (value.type) {
			case "plus":
				let have = true
				car.map((item, index) => {
					if (item.id == value.id) {
						item.number++
						have = false
					}
				})
				if (have) {
					value.obj.number = value.number || 1
					car.push(value.obj)
				}
				break
			case "reduce":
				car.map((item, index) => {
					if (item.id == value.id) {
						item.number--
					}
				})
				break
			case "delete":
				car.map((item, index) => {
					if (item.id == value.id) {
						car.splice(index, 1)
					}
				})
				break
		}

		// 计算总价 和 数量
		let number = 0,
			money = 0
		car.map(item => {
			number += item.number
			money += item.number * item.price
		})

		state.shop_car = car
		state.shop_money = money.toFixed(2)
		state.shop_number = number

		// 存储
		let data = {
			shop_car: car,
			shop_money: money.toFixed(2),
			shop_number: number
		}
		uni.setStorageSync("set_init_shop_shop_car", data)
	},
	// 数据保存 后取出
	[SHOP_SHOP_CAR_INFO]: (state, value) => {
		state.shop_car = value.shop_car || []
		state.shop_money = value.shop_money || 0.00
		state.shop_number = value.shop_number || 0
	},
	// 清空购物车
	[SHOP_SHOP_CAR_CLEAR]: (state, value) => {
		state.shop_car = []
		state.shop_money = 0.00
		state.shop_number = 0
		// 存储
		let data = {
			shop_car: [],
			shop_money: 0.00,
			shop_number: 0
		}
		uni.setStorageSync("set_init_shop_shop_car", data)
	}
}

const actions = {
	async set_change_shop_shop_car({
		commit
	}, value) {
		commit(SHOP_SHOP_CAR, value)
	},
	async set_init_shop_shop_car({
		commit
	}, value) {
		commit(SHOP_SHOP_CAR_INFO, value)
	},
	async set_clear_shop_shop_car({
		commit
	}, value) {
		commit(SHOP_SHOP_CAR_CLEAR, value)
	}
}

export default {
	state,
	mutations,
	actions
}
